<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="重复密码检查"
    width="700px"
    :close-on-click-modal="false"
  >
    <div class="duplicate-container">
      <!-- 检查结果统计 -->
      <div class="summary-section">
        <div class="summary-cards">
          <div class="summary-card">
            <div class="card-title">总账号数</div>
            <div class="card-value">{{ totalAccounts }}</div>
          </div>
          <div class="summary-card duplicate">
            <div class="card-title">重复密码组</div>
            <div class="card-value">{{ duplicateGroups.length }}</div>
          </div>
          <div class="summary-card">
            <div class="card-title">涉及账号</div>
            <div class="card-value">{{ duplicateAccountsCount }}</div>
          </div>
          <div class="summary-card risk">
            <div class="card-title">风险等级</div>
            <div class="card-value">{{ riskLevel }}</div>
          </div>
        </div>
      </div>

      <!-- 重复密码列表 -->
      <div class="duplicates-section">
        <div class="section-header">
          <h4>重复密码详情</h4>
          <el-button 
            v-if="duplicateGroups.length > 0"
            type="danger" 
            size="small" 
            @click="showBatchUpdateDialog = true"
          >
            批量更新密码
          </el-button>
        </div>

        <div v-if="duplicateGroups.length === 0" class="no-duplicates">
          <el-empty description="未发现重复密码，密码安全性良好！">
            <template #image>
              <el-icon size="60" color="#67C23A">
                <SuccessFilled />
              </el-icon>
            </template>
          </el-empty>
        </div>

        <div v-else class="duplicate-groups">
          <div
            v-for="(group, index) in duplicateGroups"
            :key="index"
            class="duplicate-group"
          >
            <div class="group-header">
              <div class="group-info">
                <span class="group-title">密码组 {{ index + 1 }}</span>
                <span class="group-count">{{ group.accounts.length }} 个账号使用相同密码</span>
              </div>
              <div class="group-actions">
                <el-button 
                  size="small" 
                  type="primary"
                  @click="generateNewPasswords(group)"
                >
                  生成新密码
                </el-button>
              </div>
            </div>
            
            <div class="group-accounts">
              <div
                v-for="account in group.accounts"
                :key="account.id"
                class="account-item"
              >
                <div class="account-info">
                  <div class="account-name">{{ account.name }}</div>
                  <div class="account-username">{{ account.username }}</div>
                  <div class="account-category">{{ getCategoryName(account.category) }}</div>
                </div>
                <div class="account-actions">
                  <el-button 
                    size="small" 
                    type="text"
                    @click="editAccount(account)"
                  >
                    编辑
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">关闭</el-button>
        <el-button type="primary" @click="exportReport">导出报告</el-button>
      </div>
    </template>

    <!-- 批量更新密码对话框 -->
    <el-dialog
      v-model="showBatchUpdateDialog"
      title="批量更新密码"
      width="500px"
      append-to-body
    >
      <div class="batch-update-content">
        <el-alert
          title="安全提醒"
          description="将为所有重复密码的账号生成新的强密码。请确保您能够安全地更新这些账号的实际密码。"
          type="warning"
          :closable="false"
          style="margin-bottom: 16px"
        />
        
        <div class="update-options">
          <el-checkbox v-model="autoSave">自动保存更新后的密码</el-checkbox>
          <el-checkbox v-model="generateReport">生成更新报告</el-checkbox>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showBatchUpdateDialog = false">取消</el-button>
          <el-button type="primary" @click="performBatchUpdate">确认更新</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'edit-account'])

const accountsStore = useAccountsStore()
const showBatchUpdateDialog = ref(false)
const autoSave = ref(true)
const generateReport = ref(true)

// 分析重复密码
const duplicateGroups = computed(() => {
  const passwordMap = new Map()
  
  // 按密码分组
  accountsStore.accounts.forEach(account => {
    if (!passwordMap.has(account.password)) {
      passwordMap.set(account.password, [])
    }
    passwordMap.get(account.password).push(account)
  })
  
  // 过滤出重复的密码组（超过1个账号使用同一密码）
  return Array.from(passwordMap.entries())
    .filter(([password, accounts]) => accounts.length > 1)
    .map(([password, accounts]) => ({
      password,
      accounts: accounts.sort((a, b) => {
        if (a.name < b.name) return -1
        if (a.name > b.name) return 1
        return 0
      })
    }))
    .sort((a, b) => b.accounts.length - a.accounts.length) // 按账号数量降序排列
})

// 计算统计数据
const totalAccounts = computed(() => accountsStore.accounts.length)
const duplicateAccountsCount = computed(() => 
  duplicateGroups.value.reduce((total, group) => total + group.accounts.length, 0)
)

const riskLevel = computed(() => {
  if (duplicateGroups.value.length === 0) return '低'
  if (duplicateGroups.value.length <= 2) return '中'
  return '高'
})

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    work: '工作',
    personal: '个人',
    social: '社交媒体',
    finance: '金融理财',
    entertainment: '游戏娱乐',
    shopping: '购物网站'
  }
  return categoryMap[category] || '其他'
}

// 生成新密码
const generatePassword = () => {
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const lowercase = 'abcdefghijklmnopqrstuvwxyz'
  const numbers = '0123456789'
  const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?'
  
  const allChars = uppercase + lowercase + numbers + symbols
  let password = ''
  
  // 确保包含各种字符类型
  password += uppercase[Math.floor(Math.random() * uppercase.length)]
  password += lowercase[Math.floor(Math.random() * lowercase.length)]
  password += numbers[Math.floor(Math.random() * numbers.length)]
  password += symbols[Math.floor(Math.random() * symbols.length)]
  
  // 添加随机字符到16位
  for (let i = 4; i < 16; i++) {
    password += allChars[Math.floor(Math.random() * allChars.length)]
  }
  
  // 打乱字符顺序
  return password.split('').sort(() => Math.random() - 0.5).join('')
}

// 为一组账号生成新密码
const generateNewPasswords = async (group) => {
  try {
    const result = await ElMessageBox.confirm(
      `将为这 ${group.accounts.length} 个账号生成新的唯一密码，是否继续？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      const updates = []
      
      // 为每个账号生成新密码
      group.accounts.forEach(account => {
        const newPassword = generatePassword()
        updates.push({
          ...account,
          password: newPassword,
          updatedAt: new Date().toISOString()
        })
      })
      
      // 批量更新
      for (const updatedAccount of updates) {
        await accountsStore.updateAccount(updatedAccount.id, updatedAccount)
      }
      
      ElMessage.success(`已为 ${updates.length} 个账号生成新密码`)
    }
  } catch (error) {
    console.error('生成新密码失败:', error)
    ElMessage.error('生成新密码失败')
  }
}

// 批量更新所有重复密码
const performBatchUpdate = async () => {
  try {
    let totalUpdated = 0
    const updateReport = []
    
    for (const group of duplicateGroups.value) {
      for (const account of group.accounts) {
        const newPassword = generatePassword()
        const updatedAccount = {
          ...account,
          password: newPassword,
          updatedAt: new Date().toISOString()
        }
        
        if (autoSave.value) {
          await accountsStore.updateAccount(account.id, updatedAccount)
        }
        
        updateReport.push({
          accountName: account.name,
          username: account.username,
          oldPasswordLength: account.password.length,
          newPasswordLength: newPassword.length,
          updateTime: new Date().toLocaleString()
        })
        
        totalUpdated++
      }
    }
    
    if (generateReport.value) {
      const report = {
        updateTime: new Date().toLocaleString(),
        totalUpdated,
        accounts: updateReport
      }
      
      const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `密码更新报告_${new Date().toISOString().split('T')[0]}.json`
      a.click()
      URL.revokeObjectURL(url)
    }
    
    showBatchUpdateDialog.value = false
    ElMessage.success(`已成功更新 ${totalUpdated} 个账号的密码`)
    
  } catch (error) {
    console.error('批量更新失败:', error)
    ElMessage.error('批量更新失败')
  }
}

// 编辑账号
const editAccount = (account) => {
  emit('edit-account', account)
}

// 导出报告
const exportReport = () => {
  const report = {
    date: new Date().toLocaleString(),
    totalAccounts: totalAccounts.value,
    duplicateGroups: duplicateGroups.value.length,
    duplicateAccountsCount: duplicateAccountsCount.value,
    riskLevel: riskLevel.value,
    details: duplicateGroups.value.map((group, index) => ({
      groupId: index + 1,
      accountsCount: group.accounts.length,
      accounts: group.accounts.map(account => ({
        name: account.name,
        username: account.username,
        category: getCategoryName(account.category)
      }))
    }))
  }
  
  const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `重复密码检查报告_${new Date().toISOString().split('T')[0]}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('报告导出成功')
}
</script>

<style scoped>
.duplicate-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.summary-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.summary-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  border: 2px solid transparent;
}

.summary-card.duplicate {
  border-color: #e53e3e;
  background: #fed7d7;
}

.summary-card.risk {
  border-color: #d69e2e;
  background: #feebc8;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.no-duplicates {
  text-align: center;
  padding: 40px 20px;
}

.duplicate-groups {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.duplicate-group {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e6e6e6;
}

.group-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.group-title {
  font-weight: 600;
  color: #333;
}

.group-count {
  font-size: 12px;
  color: #e53e3e;
  font-weight: 500;
}

.group-accounts {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.account-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
}

.account-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.account-name {
  font-weight: 500;
  color: #333;
}

.account-username {
  font-size: 12px;
  color: #666;
}

.account-category {
  font-size: 11px;
  color: #999;
  background: #e6e6e6;
  padding: 2px 6px;
  border-radius: 3px;
  align-self: flex-start;
}

.batch-update-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.update-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
